package com.zzy.database.service.Impl;

import com.zzy.database.mapper.TransactionMapper;
import com.zzy.database.pojo.transaction;
import com.zzy.database.service.TransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

@Service
public class TransactionServiceImpl implements TransactionService {

    @Autowired
    private TransactionMapper transactionMapper;

    @Override
    @Transactional
    public boolean deposit(int accountId, double amount) {
        if (amount <= 0)
            return false;

        // 创建交易记录
        transaction trans = new transaction(
                UUID.randomUUID().toString(),
                accountId,
                amount,
                "存款",
                new Date(),
                0);

        // 更新账户余额并插入交易记录
        return transactionMapper.updateAccountBalance(accountId, amount) > 0
                && transactionMapper.insertTransaction(trans) > 0;
    }

    @Override
    @Transactional
    public boolean withdraw(int accountId, double amount) {
        if (amount <= 0)
            return false;

        // 检查余额是否充足
        double balance = transactionMapper.getAccountBalance(accountId);
        if (balance < amount)
            return false;

        // 创建交易记录
        transaction trans = new transaction(
                UUID.randomUUID().toString(),
                accountId,
                -amount,
                "取款",
                new Date(),
                0);

        // 更新账户余额并插入交易记录
        return transactionMapper.updateAccountBalance(accountId, -amount) > 0
                && transactionMapper.insertTransaction(trans) > 0;
    }

    @Override
    @Transactional
    public boolean transfer(int fromAccountId, int toAccountId, double amount) {
        if (amount <= 0)
            return false;
        // 检查转出账户余额是否充足
        double balance = transactionMapper.getAccountBalance(fromAccountId);
        if (balance < amount)
            return false;

        // 创建转出交易记录
        transaction transOut = new transaction(
                UUID.randomUUID().toString(),
                fromAccountId,
                -amount,
                "转账",
                new Date(),
                toAccountId);

        // 创建转入交易记录
        transaction transIn = new transaction(
                UUID.randomUUID().toString(),
                toAccountId,
                amount,
                "转账",
                new Date(),
                fromAccountId);

        // 执行转账操作
        return transactionMapper.updateAccountBalance(fromAccountId, -amount) > 0
                && transactionMapper.updateAccountBalance(toAccountId, amount) > 0
                && transactionMapper.insertTransaction(transOut) > 0
                && transactionMapper.insertTransaction(transIn) > 0;
    }
}
